package controller

import (
	"context"

	tableComm "gitee.com/klein-x/biz/model/mysql/table/comm"
	"gitee.com/klein-x/biz/xutils"
)

const (
	COMM_DB_ERROR            = 9900
	COMM_MAKE_ORDER_ID_ERROR = 3001
	COMM_INVAILD_GOODS_ID    = 3002
)

func MakeOrder(ctx context.Context, uid string, goodsId string) (*string, error) {
	//查询商品
	goods, err := tableComm.GoodsGetByKey(goodsId)
	if err != nil {
		return nil, xutils.Error(COMM_DB_ERROR, err)
	}
	if goods == nil {
		return nil, xutils.Error(COMM_INVAILD_GOODS_ID, "无效的商品ID")
	}

	orderId := xutils.GenerateOrderId()
	if orderId == "" {
		return nil, xutils.Error(COMM_MAKE_ORDER_ID_ERROR, "生成订单id失败")
	}

	// 创建Order
	var ord tableComm.Order
	ord.ID = orderId
	ord.UserID = uid
	ord.GoodsID = goods.GoodsID
	ord.GoodsName = goods.Name
	ord.Price = goods.Price
	ord.Quantity = 1
	ord.TotalAmount = ord.Price
	ord.Status = "0"

	if err := tableComm.OrderInsert(&ord); err != nil {
		return nil, xutils.Error(COMM_DB_ERROR, err)
	} else {
		return &orderId, nil
	}
}

func GetUserOrderSummarys(ctx context.Context, uid string) (*[]OrderSummary, error) {
	var orderList []OrderSummary
	// 查询订单列表
	userOrder, err := tableComm.OrderGetByUser(uid)
	if err != nil {
		return nil, xutils.Error(COMM_DB_ERROR, err)
	}

	for _, order := range *userOrder {
		var item OrderSummary

		item.OrderId = order.ID
		item.GoodsID = order.GoodsID
		item.GoodsName = order.GoodsName
		item.TotalAmount = order.TotalAmount
		item.CreatedAt = order.CreatedAt.Format("2006-01-02 15:04:05")
		item.Status = order.Status

		goods, err := tableComm.GoodsGetByKey(order.GoodsID)
		if err == nil && goods != nil {
			item.GoodsThumbnail = goods.Thumbnail
		}

		orderList = append(orderList, item)
	}

	return &orderList, nil
}

func GetUserOrderDetail(ctx context.Context, uuid string, orderId string) (*OrderDetail, error) {
	tableOrder, err := tableComm.OrderGetByKeyAndUser(orderId, uuid)
	if err != nil {
		return nil, xutils.Error(COMM_DB_ERROR, err)
	}

	if tableOrder == nil {
		return nil, nil
	}

	var order OrderDetail

	order.OrderId = tableOrder.ID
	order.GoodsID = tableOrder.GoodsID
	order.GoodsName = tableOrder.GoodsName
	order.Price = tableOrder.Price
	order.Quantity = tableOrder.Quantity
	order.TotalAmount = tableOrder.TotalAmount
	order.CreatedAt = tableOrder.CreatedAt.Format("2006-01-02 15:04:05")
	order.UpdatedAt = tableOrder.UpdatedAt.Format("2006-01-02 15:04:05")
	order.Status = tableOrder.Status

	return &order, nil
}
